<?php
namespace SinoPHP\BbdBoss\Model;

use Upfor\UpforPHP\Model;

class BasicInformation extends Model {

    /**
     * 更新IP列表
     *
     * @param array $list
     */
    public function getServerIpList($startTime, $endTime) {
        $fields = 'ip,hostname,server_area,server_area_id,sync_ip_id,isp,physical_node,physical_node_id,device_number,device_number_id,relate_port,large_area,country,province,city,province_abbreviate,city_abbreviate,is_delete';
        $where = ['belong_type' => 1, 'update_time|<>' => [$startTime, $endTime]];
        $this->setTableName('server_ip_mix');

        return $this->getList($fields, $where);
    }

    /**
     * @param $ids 要下架的ip 的id
     * @return array false:不可以下架/true:可以下架
     */
    public function checkIsUsed($ids) {
        $result = ['status' => false, 'ip_id' => 0];
        $whereInnerDomain['is_delete'] = 0;
        $whereInnerDomain['ip_id'] = $ids;
        //存在备记录 或 查询失败 返回FALSE
        $this->setTableName('inner_domain_bak_record');
        $innerDomainBak = $this->getRow('ip_id', $whereInnerDomain);
        if ($innerDomainBak || $innerDomainBak === false) {
            $result['ip_id'] = $innerDomainBak['ip_id'];
            return $result;
        }
        //存在主记录 或 查询失败 返回FALSE
        $this->setTableName('inner_domain_master_record');
        $innerDomainMas = $this->getRow('master_record_id', $whereInnerDomain);
        if ($innerDomainMas || $innerDomainMas === false) {
            $result['ip_id'] = $innerDomainMas['ip_id'];
            return $result;
        }
        //被服务器绑定 或 查询失败 返回FALSE
        $this->setTableName('server_group_ip');
        $serverGroupIp = $this->getRow('ip_id', ['ip_id' => $ids]);
        if ($serverGroupIp || $serverGroupIp === false) {
            $result['ip_id'] = $serverGroupIp['ip_id'];
            return $result;
        }
        //被虚拟节点绑定 返回FALSE
        $this->setTableName('virtual_node');
        $virtualNode = $this->getList('server_ip_id,real_ip_ids');
        if ($virtualNode === false) {
            return $result;
        }
        if (empty($virtualNode)) {
            $result['status'] = true;
            return $result;
        }

        $ipIdStr = '';
        foreach ($virtualNode as $key => $value) {
            $ipIdStr .= $value['server_ip_id'] . ',' . $value['real_ip_ids'] . ',';
        }
        $ipIdArray = array_unique(explode(',', $ipIdStr));
        $intersectIP = array_intersect($ids, $ipIdArray);
        if ($intersectIP) {
            $result['ip_id'] = array_pop($intersectIP);
            return $result;
        }
        $result['status'] = true;
        return $result;
    }

}
